<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车 - HUAWEI Global Store</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .cart-icon {
            position: relative;
            padding: 10px;
            background: rgba(255,255,255,0.3);
            border-radius: 50%;
            cursor: pointer;
        }

        .cart-count {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #ef4444;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* Breadcrumb */
        .breadcrumb {
            background: white;
            padding: 15px 0;
            border-bottom: 1px solid #e5e7eb;
        }

        .breadcrumb-list {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
        }

        .breadcrumb-list a {
            color: #6b7280;
            text-decoration: none;
        }

        .breadcrumb-list a:hover {
            color: #3b82f6;
        }

        .breadcrumb-separator {
            color: #9ca3af;
        }

        /* Cart Page */
        .cart-page {
            padding: 40px 0;
            min-height: 70vh;
        }

        .page-title {
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 30px;
            color: #1f2937;
        }

        .cart-container {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 40px;
        }

        .cart-items {
            background: white;
            border-radius: 20px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
            overflow: hidden;
        }

        .cart-header {
            padding: 20px 30px;
            background: #f8fafc;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .cart-header h3 {
            font-size: 20px;
            font-weight: 600;
        }

        .select-all {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .cart-items-list {
            max-height: 500px;
            overflow-y: auto;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f8fafc;
            color: #1f2937;
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        /* Header */
        .header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            padding: 15px 0;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            font-size: 28px;
            font-weight: bold;
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
        }

        .logo::before {
            content: "🌐";
            font-size: 24px;
        }

        .nav {
            display: flex;
            gap: 30px;
            align-items: center;
        }

        .nav a {
            color: white;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
            padding: 10px 15px;
            border-radius: 8px;
        }

        .nav a:hover {
            background: rgba(255,255,255,0.2);
            transform: translateY(-2px);
        }

        .user-actions {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .cart-items-list {
            padding: 0;
        }

        .cart-item {
            display: flex;
            gap: 20px;
            padding: 30px;
            border-bottom: 1px solid #f3f4f6;
            transition: all 0.3s ease;
        }

        .cart-item:last-child {
            border-bottom: none;
        }

        .cart-item:hover {
            background: #f8fafc;
        }

        .item-checkbox {
            display: flex;
            align-items: center;
            margin-right: 10px;
        }

        .item-checkbox input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }

        .cart-item-image {
    width: 100px;          /* 固定宽度，可以按需要调整 */
    height: 100px;         /* 固定高度 */
    display: flex;
    align-items: center;   /* 垂直居中 */
    justify-content: center; /* 水平居中 */
    overflow: hidden;      /* 防止图片超出容器 */
    border-radius: 8px;    /* 圆角效果，可选 */
    background: #f9f9f9;   /* 背景色，增强对比，可选 */
    cursor: pointer;       /* 鼠标移上去是小手 */
}

        .cart-item-image:hover {
            transform: scale(1.02);
        }

        .cart-item-details {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .cart-item-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #1f2937;
        }

        .cart-item-specs {
            color: #6b7280;
            margin-bottom: 10px;
            display: flex;
            gap: 15px;
        }

        .spec-item {
            background: #f1f5f9;
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 14px;
        }

        .cart-item-price {
            font-size: 24px;
            font-weight: bold;
            color: #3b82f6;
        }

        .original-price {
            font-size: 16px;
            color: #9ca3af;
            text-decoration: line-through;
            margin-right: 10px;
        }

        .cart-item-actions {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: flex-end;
            min-width: 150px;
        }

        .remove-item {
            color: #ef4444;
            cursor: pointer;
            padding: 8px;
            border-radius: 5px;
            transition: all 0.3s ease;
            font-size: 14px;
            background: none;
            border: none;
        }

        .remove-item:hover {
            background: #fee2e2;
        }

        .quantity-controls {
            display: flex;
            align-items: center;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            background: white;
            margin-top: 15px;
        }

        .quantity-btn {
            width: 35px;
            height: 35px;
            border: none;
            background: none;
            cursor: pointer;
            font-size: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .quantity-btn:hover {
            background: #f3f4f6;
        }

        .quantity-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .quantity-input {
            width: 50px;
            height: 35px;
            border: none;
            text-align: center;
            font-size: 16px;
            font-weight: 600;
        }

        /* Cart Summary */
        .cart-summary {
            background: white;
            padding: 30px;
            border-radius: 20px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
            height: fit-content;
            position: sticky;
            top: 120px;
        }

        .summary-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 25px;
            color: #1f2937;
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
            color: #6b7280;
        }

        .summary-row.total {
            font-size: 20px;
            font-weight: bold;
            color: #1f2937;
            border-top: 2px solid #f3f4f6;
            padding-top: 20px;
            margin-top: 20px;
        }

        .savings {
            color: #10b981;
            font-weight: 600;
        }

        .promo-code {
            margin-bottom: 25px;
        }

        .promo-code h4 {
            margin-bottom: 15px;
            color: #1f2937;
        }

        .promo-input {
            display: flex;
            gap: 10px;
        }

        .promo-input input {
            flex: 1;
            padding: 12px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .promo-input input:focus {
            outline: none;
            border-color: #3b82f6;
        }

        .btn {
            padding: 15px 30px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            color: white;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, #1d4ed8, #1e40af);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
        }

        .btn-primary:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .btn-outline {
            background: white;
            border: 2px solid #3b82f6;
            color: #3b82f6;
        }

        .btn-outline:hover {
            background: #3b82f6;
            color: white;
        }

        .btn-small {
            padding: 8px 16px;
            font-size: 14px;
        }

        .btn-full {
            width: 100%;
        }

        /* Empty Cart */
        .empty-cart {
            text-align: center;
            padding: 80px 20px;
            background: white;
            border-radius: 20px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
        }

        .empty-cart-icon {
            font-size: 80px;
            margin-bottom: 30px;
            opacity: 0.5;
        }

        .empty-cart h3 {
            font-size: 24px;
            margin-bottom: 15px;
            color: #1f2937;
        }

        .empty-cart p {
            color: #6b7280;
            margin-bottom: 30px;
            font-size: 16px;
        }

        /* Recommended Products */
        .recommended-products {
            margin-top: 50px;
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
        }

        .recommended-products h3 {
            margin-bottom: 25px;
            color: #1f2937;
        }

        .recommended-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }

        .recommended-item {
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .recommended-item:hover {
            border-color: #3b82f6;
            transform: translateY(-2px);
        }

        .recommended-item-image {
            width: 100%;
            height: 120px;
            background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 36px;
            margin-bottom: 10px;
        }

        .recommended-item-title {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .recommended-item-price {
            color: #3b82f6;
            font-weight: bold;
            margin-bottom: 10px;
        }

        /* Security Badge */
        .security-info {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 20px;
            background: #f0f9f4;
            border-radius: 10px;
            margin-bottom: 25px;
        }

        .security-icon {
            font-size: 24px;
            color: #10b981;
        }

        .security-text {
            flex: 1;
        }

        .security-title {
            font-weight: 600;
            color: #065f46;
            margin-bottom: 2px;
        }

        .security-desc {
            font-size: 14px;
            color: #047857;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .cart-container {
                grid-template-columns: 1fr;
            }

            .cart-item {
                flex-direction: column;
                gap: 15px;
            }

            .cart-item-image {
                width: 100px;
                height: 100px;
                font-size: 28px;
                align-self: flex-start;
            }

            .cart-item-actions {
                flex-direction: row;
                justify-content: space-between;
                align-items: center;
                min-width: auto;
            }

            .quantity-controls {
                margin-top: 0;
            }

            .nav {
                display: none;
            }

            .promo-input {
                flex-direction: column;
            }
        }

        /* Animations */
        .fade-in {
            animation: fadeIn 0.6s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .slide-out {
            animation: slideOut 0.3s ease-in-out forwards;
        }

        @keyframes slideOut {
            from { transform: translateX(0); opacity: 1; }
            to { transform: translateX(100%); opacity: 0; }
        }

        /* Loading Animation */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f4f6;
            border-top: 2px solid #3b82f6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Notification */
        .notification {
            position: fixed;
            top: 100px;
            right: 20px;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            border-left: 4px solid #10b981;
            z-index: 3000;
            animation: slideInRight 0.3s ease;
            min-width: 250px;
        }

        .notification.error {
            border-left-color: #ef4444;
        }

        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
     <header class="header">
        <div class="container">
            <div class="header-content">
                <div class="logo" onclick="window.location.href='index.html'">HUAWEI Global Store</div>
                <nav class="nav">
                    <a href="index.html">首页</a>
                    <a href="product-list.html">新品</a>
                    <a href="support.html">支持</a>
                    <a href="about.html">关于</a>
                    
                </nav>
                <div class="user-actions">
                    <select style="padding: 8px; border-radius: 5px; border: none;">
                        <option>🇨🇳 中文</option>
                        <option>🇺🇸 English</option>
                        <option>🇯🇵 日本語</option>
                        <option>🇩🇪 Deutsch</option>
                    </select>
                    <div class="cart-icon">
                        🛒
                        <div class="cart-count" id="cartCount">0</div>
                    </div>
                    <button id="loginBtn" 
        class="btn btn-outline" 
        style="padding: 8px 16px; background: transparent; border: 2px solid white; color: white;" 
        onclick="openLoginModal()">登录</button>

                <button id="profileBtn" class="btn btn-outline" style="padding: 8px 16px; background: transparent; border: 2px solid white; color: white;" onclick="handleProfileClick()">个人中心</button>
                </div>
            </div>
        </div>
    </header>

    <!-- Breadcrumb -->
    <nav class="breadcrumb">
        <div class="container">
            <div class="breadcrumb-list">
                <a href="index.html">首页</a>
                <span class="breadcrumb-separator">></span>
                <span>购物车</span>
            </div>
        </div>
    </nav>

    <!-- Cart Page -->
    <section class="cart-page">
        <div class="container">
            <h1 class="page-title fade-in">购物车</h1>
            
            <div class="cart-container" id="cartContainer">
                <!-- Cart Items -->
                <div class="cart-items fade-in">
                    <div class="cart-header">
                        <h3>商品信息</h3>
                        <div class="select-all">
                            <input type="checkbox" id="selectAll" onchange="selectAllItems()">
                            <label for="selectAll">全选</label>
                        </div>
                    </div>
                    <div class="cart-items-list" id="cartItemsList">
                        <!-- 购物车商品将通过JavaScript动态加载 -->
                    </div>
                </div>

                <!-- Cart Summary -->
                <div class="cart-summary fade-in">
                    <h3 class="summary-title">订单摘要</h3>
                    
                    <div class="security-info">
                        <div class="security-icon">🔒</div>
                        <div class="security-text">
                            <div class="security-title">安全支付保障</div>
                            <div class="security-desc">256位SSL加密，保护您的支付安全</div>
                        </div>
                    </div>

                    <!-- 商品明细列表 -->
                    <div class="summary-items-list" id="summaryItemsList">
                        <!-- JS 会动态生成每行商品的小计 -->
                        <!-- 示例：
                        <div class="summary-item">
                            <span>华为Mate 70 Pro × 1</span>
                            <span>¥7599</span>
                        </div>
                        -->
                    </div>
                    
                    <div class="summary-row">
                        <span>商品小计 (<span id="selectedCount">0</span>件):</span>
                        <span id="subtotal">¥0</span>
                    </div>
                    <div class="summary-row">
                        <span>运费:</span>
                        <span id="shipping">免运费</span>
                    </div>
                    <div class="summary-row">
                        <span>优惠金额:</span>
                        <span class="savings" id="discount">-¥0</span>
                    </div>
                    <div class="summary-row total">
                        <span>总计:</span>
                        <span id="total">¥0</span>
                    </div>
                    
                    <div class="promo-code">
                        <h4>优惠券</h4>
                        <div class="promo-input">
                            <input type="text" placeholder="输入优惠码" id="promoInput">
                            <button class="btn btn-outline btn-small" onclick="applyPromo()">应用</button>
                        </div>
                    </div>
                    
                    <button class="btn btn-primary btn-full" id="checkoutBtn" onclick="window.location.href='checkout.html'">
                        结算 (<span id="checkoutCount">0</span>)
                    </button>

                    
                    <div style="text-align: center; margin-top: 15px;">
                        <a href="index.html" style="color: #6b7280; text-decoration: none; font-size: 14px;">继续购物</a>
                    </div>
                </div>

            </div>

            <!-- Empty Cart State -->
            <div class="empty-cart" id="emptyCart" style="display: none;">
                <div class="empty-cart-icon">🛒</div>
                <h3>购物车是空的</h3>
                <p>看起来您还没有添加任何商品到购物车</p>
                <button class="btn btn-primary" onclick="window.location.href='index.html'">
                    立即购物
                </button>
            </div>

            <!-- Recommended Products -->
            <style>
/* 图片大小控制核心样式 */
.recommended-item-image {
    /* 父容器固定尺寸，避免图片溢出 */
    width: 100%;
    height: 220px; /* 可根据需求调整图片区域高度 */
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5; /* 图片加载前的占位背景色，可选 */
    border-radius: 8px; /* 可选：给图片区域加圆角，优化视觉 */
}

.recommended-img {
    /* 图片自适应父容器，同时保持比例 */
    width: 100%;
    height: 100%;
    object-fit: cover; /* 关键属性：图片完整填充区域，不拉伸（超出部分裁剪） */
    object-position: center; /* 图片居中显示，避免裁剪关键部分 */
    border-radius: 6px; /* 可选：给图片加圆角，与父容器呼应 */
}

/* 可选：响应式适配（小屏幕自动调整图片高度） */
@media (max-width: 768px) {
    .recommended-item-image {
        height: 180px; /* 手机等小屏幕下，适当减小图片高度 */
    }
}
</style>

<div class="recommended-products fade-in" id="recommendedProducts">
    <h3>为您推荐</h3>
    <div class="recommended-grid">
        <!-- 华为WATCH GT 5 -->
        <div class="recommended-item" onclick="window.location.href='product-detail.html'">
            <div class="recommended-item-image">
                <img src="images/1.png" alt="华为WATCH GT 5" class="recommended-img">
            </div>
            <div class="recommended-item-title">华为WATCH GT 5</div>
            <div class="recommended-item-price">¥2,199</div>
            <button class="btn btn-outline btn-small">查看详情</button>
        </div>
        <!-- 华为FreeBuds Pro 4 -->
        <div class="recommended-item" onclick="window.location.href='product-detail.html'">
            <div class="recommended-item-image">
                <img src="images/1.png" alt="华为FreeBuds Pro 4" class="recommended-img">
            </div>
            <div class="recommended-item-title">华为FreeBuds Pro 4</div>
            <div class="recommended-item-price">¥1,399</div>
            <button class="btn btn-outline btn-small">查看详情</button>
        </div>
        <!-- 华为MateBook X Pro -->
        <div class="recommended-item" onclick="window.location.href='product-detail.html'">
            <div class="recommended-item-image">
                <img src="images/1.png" alt="华为MateBook X Pro" class="recommended-img">
            </div>
            <div class="recommended-item-title">华为MateBook X Pro</div>
            <div class="recommended-item-price">¥8,999</div>
            <button class="btn btn-outline btn-small">查看详情</button>
        </div>
        <!-- 华为SuperCharge充电器 -->
        <div class="recommended-item" onclick="window.location.href='product-detail.html'">
            <div class="recommended-item-image">
                <img src="images/1.png" alt="华为SuperCharge充电器" class="recommended-img">
            </div>
            <div class="recommended-item-title">华为SuperCharge充电器</div>
            <div class="recommended-item-price">¥299</div>
            <button class="btn btn-outline btn-small">查看详情</button>
        </div>
    </div>
</div>
        </div>
    </section>

    <script>
    let cart = [];
    let selectedItems = new Set();
    let promoDiscount = 0;

    // 页面加载时初始化购物车
    document.addEventListener('DOMContentLoaded', function() {
        loadCart();
        updateCartDisplay();
    });

    // 加载购物车数据
    function loadCart() {
        const savedCart = localStorage.getItem('cart');
        if (savedCart) {
            cart = JSON.parse(savedCart);
        }

        // 如果购物车为空，添加一些示例数据
      if (cart.length === 0) {
    cart = [
        {
            id: 1,
            name: '华为Mate 70 Pro',
            storage: '512GB',
            color: '雅黑',
            price: 7599,
            originalPrice: 7999,
            quantity: 1,
            image: 'images/1.png' // 对应手机的专属数字路径（避免与手表重复）
        },
        {
            id: 2,
            name: '华为WATCH GT 5',
            storage: '46mm',
            color: '星河银',
            price: 2199,
            originalPrice: 2399,
            quantity: 1,
            image: 'images/2.png' // 对应手表的专属数字路径（避免与手机重复）
        },
        {
            id: 3,
            name: '华为FreeBuds Pro 3',
            storage: '主动降噪耳机',
            color: '碳晶黑',
            price: 1499,
            originalPrice: 1699,
            quantity: 2,
            image: 'images/3.png' // 对应耳机的专属数字路径（每个商品唯一）
        }
    ];
    saveCart(); // 保留原购物车保存逻辑
}
    }

    // 保存购物车到本地存储
    function saveCart() {
        localStorage.setItem('cart', JSON.stringify(cart));
    }

    // 更新购物车显示
    function updateCartDisplay() {
        const cartItemsList = document.getElementById('cartItemsList');
        const emptyCart = document.getElementById('emptyCart');
        const cartContainer = document.getElementById('cartContainer');
        const recommendedProducts = document.getElementById('recommendedProducts');
        
        if (cart.length === 0) {
            cartContainer.style.display = 'none';
            recommendedProducts.style.display = 'none';
            emptyCart.style.display = 'block';
            return;
        }
        
        cartContainer.style.display = 'grid';
        recommendedProducts.style.display = 'block';
        emptyCart.style.display = 'none';
        
        cartItemsList.innerHTML = '';
        
        cart.forEach((item, index) => {
            const cartItem = document.createElement('div');
            cartItem.className = 'cart-item fade-in';
            cartItem.innerHTML = `
                <div class="item-checkbox">
                    <input type="checkbox" id="item-${index}" onchange="toggleItemSelection(${index})" ${selectedItems.has(index) ? 'checked' : ''}>
                </div>
                <div class="cart-item-image" onclick="window.location.href='product-detail.html'">
    <img src="${item.image}" alt="${item.name}" class="recommended-img">
</div>

                <div class="cart-item-details">
                    <h4 class="cart-item-title">${item.name}</h4>
                    <div class="cart-item-specs">
                        <span class="spec-item">${item.storage}</span>
                        <span class="spec-item">${item.color}</span>
                    </div>
                    <div class="cart-item-price">
                        ${item.originalPrice && item.originalPrice > item.price ? 
                            `<span class="original-price">¥${item.originalPrice.toLocaleString()}</span>` : ''}
                        ¥${item.price.toLocaleString()}
                    </div>
                </div>
                <div class="cart-item-actions">
                    <button class="remove-item" onclick="removeItem(${index})">🗑️ 删除</button>
                    <div class="quantity-controls">
                        <button class="quantity-btn" onclick="updateQuantity(${index}, -1)" ${item.quantity <= 1 ? 'disabled' : ''}>−</button>
                        <input type="number" class="quantity-input" value="${item.quantity}" min="1" max="10" 
                               onchange="updateQuantity(${index}, 0, this.value)">
                        <button class="quantity-btn" onclick="updateQuantity(${index}, 1)" ${item.quantity >= 10 ? 'disabled' : ''}>+</button>
                    </div>
                </div>
            `;
            cartItemsList.appendChild(cartItem);
        });
        
        updateCartCount();
        updateSummary();
        updateSelectAllState();
    }

    // 切换商品选择状态
    function toggleItemSelection(index) {
        if (selectedItems.has(index)) {
            selectedItems.delete(index);
        } else {
            selectedItems.add(index);
        }
        updateSummary();
        updateSelectAllState();
    }

    // 全选/取消全选
    function selectAllItems() {
        const selectAll = document.getElementById('selectAll');
        if (selectAll.checked) {
            selectedItems.clear();
            cart.forEach((_, index) => selectedItems.add(index));
        } else {
            selectedItems.clear();
        }

        cart.forEach((_, index) => {
            const checkbox = document.getElementById(`item-${index}`);
            if (checkbox) checkbox.checked = selectedItems.has(index);
        });
        
        updateSummary();
    }

    // 更新全选按钮状态
    function updateSelectAllState() {
        const selectAll = document.getElementById('selectAll');
        if (selectedItems.size === cart.length && cart.length > 0) {
            selectAll.checked = true;
            selectAll.indeterminate = false;
        } else if (selectedItems.size === 0) {
            selectAll.checked = false;
            selectAll.indeterminate = false;
        } else {
            selectAll.checked = false;
            selectAll.indeterminate = true;
        }
    }

    // 更新商品数量
    function updateQuantity(index, delta = 0, newValue = undefined) {
        let quantity = cart[index].quantity;

        if (newValue !== undefined) {
            const value = parseInt(newValue);
            if (!isNaN(value) && value >= 1 && value <= 10) {
                quantity = value;
            }
        } else {
            const newQuantity = quantity + delta;
            if (newQuantity >= 1 && newQuantity <= 10) {
                quantity = newQuantity;
            }
        }

        cart[index].quantity = quantity;
        saveCart();
        updateCartDisplay();
    }

    // 更新购物车数量显示（比如导航栏购物车角标）
    function updateCartCount() {
        const cartCount = document.getElementById('cartCount');
        if (cartCount) {
            let totalQuantity = cart.reduce((sum, item) => sum + item.quantity, 0);
            cartCount.textContent = totalQuantity;
        }
    }

    // 更新结算区域
    function updateSummary() {
    let selectedCount = 0;
    let subtotal = 0;
    const summaryItemsList = document.getElementById('summaryItemsList');
    summaryItemsList.innerHTML = ''; // 清空旧明细

    cart.forEach((item, index) => {
        if (selectedItems.has(index)) {
            selectedCount += item.quantity;
            subtotal += item.price * item.quantity;

            // 添加每行商品小计
            const itemDiv = document.createElement('div');
            itemDiv.className = 'summary-item';
            itemDiv.innerHTML = `
                <span>${item.name} × ${item.quantity}</span>
                <span>¥${(item.price * item.quantity).toLocaleString()}</span>
            `;
            summaryItemsList.appendChild(itemDiv);
        }
    });

    document.getElementById('selectedCount').textContent = selectedCount;
    document.getElementById('subtotal').textContent = `¥${subtotal.toLocaleString()}`;
    document.getElementById('total').textContent = `¥${(subtotal - promoDiscount).toLocaleString()}`;
    document.getElementById('checkoutCount').textContent = selectedCount;

    updateSelectAllState();
}

</script>
  <script>  // ==========================
// 自动清缓存（24小时）
// ==========================
function autoClearCache() {
  const now = Date.now();
  const cacheExpire = 24 * 60 * 60 * 1000; // 缓存有效期：24小时
  const lastClear = parseInt(localStorage.getItem('lastClear')) || 0;

  if (now - lastClear > cacheExpire) {
    console.log('🧹 自动清缓存：超过24小时，清理本地存储数据');
    // 清理购物车、登录状态等
    localStorage.removeItem('cartItems');
    localStorage.removeItem('isLoggedIn');
    localStorage.setItem('lastClear', now);
    // 页面显示更新
    document.querySelector('.cart-count').textContent = 0;
    updateLoginState();
  }
}
window.addEventListener('load', autoClearCache);
setInterval(autoClearCache, 60 * 60 * 1000); // 每小时检查一次

// ==========================
// 登录/退出逻辑
// ==========================
function updateLoginState() {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  const loginBtn = document.getElementById('loginBtn');
  const logoutBtn = document.getElementById('logoutBtn');
  const cartCount = document.querySelector('.cart-count');

  if (isLoggedIn) {
    if (loginBtn) {
      loginBtn.disabled = true; // 禁用
      loginBtn.classList.add('disabled-btn'); // 添加禁用样式
    }
    if (logoutBtn) logoutBtn.style.display = 'inline-block';
  } else {
    if (loginBtn) {
      loginBtn.disabled = false; // 恢复可用
      loginBtn.classList.remove('disabled-btn');
    }
    if (logoutBtn) logoutBtn.style.display = 'none';

    // 未登录时清空购物车
    localStorage.removeItem('cartItems');
    if (cartCount) cartCount.textContent = 0;
  }
}


function login() {
  localStorage.setItem('isLoggedIn', 'true');
  updateLoginState();
  alert('登录成功！现在可以使用购物车和个人中心。');
}

function logout() {
  localStorage.removeItem('isLoggedIn');
  updateLoginState();
  alert('已退出登录，购物车和个人中心不可用。');
}

// ==========================
// 购物车控制
// ==========================
function handleCartClick() {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  if (!isLoggedIn) {
    alert('请先登录才能使用购物车');
    window.location.href = 'login.html';
    return;
  }
  window.location.href = 'cart.html';
}

// ==========================
// 个人中心控制
// ==========================
function handleProfileClick() {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  if (!isLoggedIn) {
    alert('请先登录才能进入个人中心');
    window.location.href = 'login.html';
    return;
  }
  window.location.href = 'user-center.html';
}

// ==========================
// 页面加载初始化
// ==========================
window.addEventListener('load', function() {
  updateLoginState();

  // 初始化购物车数量
  let cartItems = parseInt(localStorage.getItem('cartItems')) || 0;
  document.querySelector('.cart-count').textContent = cartItems;

  // 绑定点击事件（强制检查登录状态）
  const cartIcon = document.getElementById('cartIcon');
  if (cartIcon) cartIcon.addEventListener('click', handleCartClick);

  const profileIcon = document.getElementById('profileIcon');
  if (profileIcon) profileIcon.addEventListener('click', handleProfileClick);
});</script>
